<script setup>
import {ref, reactive, defineOptions, onMounted, watch} from 'vue'
import { ipcApiRoute } from "@/api";
import { ipc } from '@/utils/ipcRenderer'
import { Icon } from '@iconify/vue'
import siderTop from './siderTop/index.vue'
import {message} from "ant-design-vue";
import {useSystemSettingStore} from "@/store/systemSetting";
import { throttle } from "lodash";

let emailSvg = ref('')
import('@/assets/svg/email.svg').then(res => {
  emailSvg.value = res.default
})

defineOptions({
  name: 'EmailService'
})

const emailListRef = ref(null)
const emails = ref([])
const selected = ref(null)
const selectPaltfrom = ref('qq')

//  分页
const pagination = reactive({
  page:1,
  pageSize:32,
  total:0,
  isLoadMore: false,//是否加载更多
  hasMore: true,
})

const getEmailList = () => {
  ipc.send(ipcApiRoute.emailService.getEmailList, {type:'get:list:all',content:'', page:pagination.page,pageSize:pagination.pageSize})
}


const selectedEmail = ref(null)
const isLoadingEmailList = ref(false)
function selectEmail(email) {
  email.new ? email.new = false : null
  selectedEmail.value = email
}

function extractSenderName(from) {
  const match = from.match(/^"?([^"<@]+?)"?\s*<.*?>$/); // 匹配中文名或显示名
  if (match) return match[1].trim();

  // 如果是没有显示名的纯邮箱地址，取 @ 前部分
  const simpleEmailMatch = from.match(/^([^@]+)@/);
  return simpleEmailMatch ? simpleEmailMatch[1] : from;
}

function getInitials(from) {
  // 尝试提取 "xxx" <email> 中的显示名
  const match = from.match(/"?([^"<]+)"?\s*<.*?>/) || from.match(/([^<@]+)/)

  let name = match ? match[1].trim() : from.trim()

  // 去掉开头的特殊符号
  name = name.replace(/^[^a-zA-Z0-9\u4e00-\u9fa5]+/, '')

  if (!name) return '?'

  const firstChar = name.charAt(0)

  return firstChar.toUpperCase()
}

function formatDate(date) {
  const d = new Date(date)
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`
}

function formatTime(date) {
  const d = new Date(date)
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const init = () => {
  ipc.removeAllListeners(ipcApiRoute.emailService.getEmailList)
  ipc.removeAllListeners(ipcApiRoute.emailService.newEmail)
  isLoadingEmailList.value = true
  ipc.on(ipcApiRoute.emailService.getEmailList, (event, data) => {
    if(data.type == 'get:list:all'){
      emails.value = data.content
      isLoadingEmailList.value = false
      let allCount = soderTopUtils.value.find(i => i.key == 'all')
      pagination.total = data.total
      allCount.text = `(${data.total})条`
    }else if(data.type == 'get:list:next'){
      // console.log('data',data)
      emails.value.push(...data.content)
      pagination.isLoadMore = false
      pagination.page++
      if(data?.content.length == 0){
        pagination.hasMore = false
      }
    }
  })
  ipc.on(ipcApiRoute.emailService.newEmail,(e,data) => {
    // console.log('newEmail',data)
    if(data?.content){
      data.content["new"] = true
      emails.value.unshift(data.content)
    }
  })
}

const soderTopUtils = ref([{
  icon:"tdesign:usergroup",
  text: "切换",
  iconPosition:"left",
  key:"switch-user"
},{
  icon:"mdi-light:refresh",
  text:"刷新",
  iconPosition:"left",
  key:"refresh"
},{
  icon:"mdi-light:pencil",
  text:"写信",
  iconPosition:"left",
  key:"write"
},{
  // icon:"mdi-light:chevron-down",
  text:"",
  iconPosition:"right",
  key: "all"
}])

const siderTopClickHandler = (item) => {
  switch (item.key) {
    case "switch-user":
      break
    case "refresh":
      isLoadingEmailList.value = true
      pagination.page = 1
      getEmailList()
      break
    case "write":
      // 获取当前运行环境的域名
      let domain = window.location.origin
      console.log('domain',domain)
      ipc.invoke(ipcApiRoute.osService.createWin,{ type:'vue',content:'#/excelService',windowName:'write-email',windowTitle:'写邮件',webRootUrl: domain }).then(res => {
        console.log('写邮件：',res)
      })
      break
  }
}

// 切换邮箱
const switchUserEmailHandler = (tag) => {
  if(selectPaltfrom.value == tag){
    return
  }
  selectPaltfrom.value = tag
  pagination.page = 1
  pagination.total = 0
  pagination.isLoadMore = false
  pagination.hasMore = true
  isLoadingEmailList.value = true
  ipc.invoke(ipcApiRoute.emailService.switchUserAccount,{platfrom:tag}).then(res => {
    selectedEmail.value = null
    emails.value = res?.emailes
    isLoadingEmailList.value = false
    pagination.total = res?.total
    soderTopUtils.value[3].text = `(${res?.total})条`
    message.success(`已经切换为${selectPaltfrom.value}邮箱`)
  })
}

// 设置左侧列表监听加载更多
const handleScroll = throttle(() => {
  const el = emailListRef.value?.$el || emailListRef.value
  if (!el) return

  const scrollBottom = el.scrollTop + el.clientHeight
  const isBottom = scrollBottom >= el.scrollHeight

  if (isBottom && !pagination.isLoadMore && pagination.hasMore) {
    loadNextPage()
  }
}, 500) // 每 200ms 执行一次

const loadNextPage = () => {
  pagination.page == 1  ? pagination.page++ : null
  pagination.isLoadMore = true
  ipc.send(ipcApiRoute.emailService.getEmailList, {type:'get:list:next',content:'', page:pagination.page,pageSize:pagination.pageSize})
}

watch(() => selectPaltfrom.value,(newPaltFrom) => {
  soderTopUtils.value[0].text = newPaltFrom.toUpperCase()
})

onMounted(() => {
  init()
  soderTopUtils.value[0].text = selectPaltfrom.value.toUpperCase()
  getEmailList()
  const el = emailListRef.value?.$el || emailListRef.value
  el?.addEventListener('scroll', handleScroll)
})





</script>

<template>
  <div class="email-service h-full">
    <a-spin class="h-full" :spinning="isLoadingEmailList" tip="加载中...">
      <a-layout class="h-full">
        <!-- 左侧邮件列表 -->
        <a-layout-sider width="300" style="background: #fff; overflow-y: hidden">
          <div class="w-full h-12 absolute top-0 left-0 flex items-center z-10 bg-white border-r">
            <sider-top @switchUserEmail="switchUserEmailHandler" @click="siderTopClickHandler(item)" v-for="(item,index) in soderTopUtils" :icon="item.icon" :tag="item.key" :text="item.text" :icon-position="item.iconPosition"></sider-top>
          </div>
          <a-list
              ref="emailListRef"
              :loading="pagination.isLoadMore"
              :data-source="emails"
              item-layout="horizontal"
              class="email-list border-r overflow-y-auto mt-12 h-[calc(100%-3rem)]"
          >
            <template #renderItem="{ item }">
              <a-list-item
                  :class="{ 'selected': selectedEmail?.uid === item.uid }"
                  class="box-border hover:bg-gray-50 relative"
                  @click="selectEmail(item)"
                  style="padding: 12px 16px;"
              >
                <p v-if="item?.new" class="size-2 rounded-full bg-blue-700 absolute text-xs right-3 top-3 z-10"></p>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar class="text-blue-500 font-bold cursor-default" style="background-color: #edf5ff;">
                      {{ getInitials(item.from) }}
                    </a-avatar>
                  </template>
                  <template #title>
                    <div class="cursor-default" style="font-weight: 500">{{ extractSenderName(item.from) }}</div>
                  </template>
                  <template #description>
                    <div class="cursor-default" style="color: #555; font-size: 13px;">{{ item.subject }}</div>
                  </template>
                </a-list-item-meta>
                <div style="color: #999; font-size: 12px; white-space: nowrap;">{{ formatTime(item.date) }}</div>
              </a-list-item>
            </template>
          </a-list>
        </a-layout-sider>

        <!-- 右侧邮件详情 -->
        <a-layout-content style="padding: 24px; padding-top: 0px ;background: #fff; z-index: 10; overflow-y: auto;">
          <div v-if="selectedEmail">
            <div class="w-full pt-[24px] sticky top-0 left-0 bg-white z-10">
              <h2 style="font-size: 18px; font-weight: 600;">{{ selectedEmail.subject }}</h2>
              <div style="margin-bottom: 8px; color: #888;">
                {{ selectedEmail.from }} → {{ selectedEmail.to }} ｜ {{ formatDate(selectedEmail.date) }}
              </div>
              <a-divider />
            </div>
            <div class="email-body" v-html="selectedEmail.html || selectedEmail.text" />
          </div>
          <div v-else class="placeholder">
            <img :src="emailSvg" class="text-center mx-auto size-1/3 opacity-30 transition-opacity duration-500" alt="" srcset="">
            <p class="text-center">请选择一封邮件查看内容</p>
          </div>
        </a-layout-content>
      </a-layout>
    </a-spin>
  </div>
</template>

<style scoped lang="less">
:deep(.ant-layout-sider-children) { position: relative }
.selected {
  background-color: rgba(36, 131, 255, 0.1) !important;
  :deep(.ant-list-item-meta-avatar) {
    .ant-avatar {
      background: #1263ff !important;
      color: #ffffff;
    }
  }
}
.placeholder {
  color: #aaa;
  text-align: center;
  padding-top: 100px;
}
.email-body {
  line-height: 1.6;
  font-size: 15px;
  color: #333;
}

:deep(.ant-list-item-meta) {
  .ant-list-item-meta-description {
    overflow: hidden;
    display: -webkit-box;
    text-wrap: wrap;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    margin-right: 0.5rem;
  }
}
:deep(.ant-spin-container),:deep(.ant-spin-nested-loading) {
  height: 100%;
}
</style>
